import 'package:flutter/material.dart';
import 'package:flutter_1/utils/db/DatabaseHelper.dart';
import 'package:flutter_1/utils/language/message.dart';
import 'package:flutter_1/utils/popup_menu_button_widget.dart';
import 'package:flutter_1/utils/screen_size.dart';
import 'package:flutter_1/utils/style.dart';
import 'package:flutter_1/views/components/older_btn.dart';
import 'package:get/get.dart';

/// 订单详情
class OrderDetailPage extends StatefulWidget {
  Map orderData = {};
  int num = 0;
  OrderDetailPage({super.key, required this.orderData, required this.num});

  @override
  State<OrderDetailPage> createState() => _OrderDetailPageState();
}

class _OrderDetailPageState extends State<OrderDetailPage> {
  /// 用户数据
  Map userData = {};

  /// 订单数据
  Map orderData = {};
  String content = "";
  // 默认
  String _selectedStatus = '';
  String stuateData = "";
  @override
  void initState() {
    super.initState();
    _selectedStatus = judgementStatus(widget.orderData["status"]);
    orderData = widget.orderData;
    queryUser();
  }

  /// 状态列表
  List<PopupMenuEntry<String>> scaleEndDetails() {
    List<PopupMenuEntry<String>> list = [];
    List status = [
      Strem.pendingProcessing,
      Strem.processing,
      Strem.Shipped,
      Strem.Delivered,
      Strem.Cancelled
    ];
    for (var data in status) {
      list.add(
        PopupMenuItem(
          value: data,
          child: Text(data, style: const TextStyle(color: Colors.white)),
        ),
      );
    }
    return list;
  }

  /// 判断状态
  String judgementStatus(String txt) {
    String content = "";
    if (txt == '1') {
      content = Strem.pendingProcessing;
    } else if (txt == '2') {
      content = Strem.processing;
    } else if (txt == '3') {
      content = Strem.Shipped;
    } else if (txt == '4') {
      content = Strem.Delivered;
    } else if (txt == '5') {
      content = Strem.Cancelled;
    }
    return content;
  }

  /// 查找客户数据
  queryUser() async {
    var result = await DatabaseHelper.query('User_table',
        where: 'customer_code = ?',
        whereArgs: [widget.orderData["customer_code"]]);
    if (result.isNotEmpty) {
      setState(() {
        userData = result[0];
      });
    }
  }

  /// 查找订单数据
  queryOrder() async {
    var result = await DatabaseHelper.query('Order_table',
        where: 'order_id = ?', whereArgs: [orderData["order_id"]]);
    debugPrint("result ----------- $result");
    if (result.isNotEmpty) {
      setState(() {
        orderData = result[0];
      });
    }
  }

  /// 删除订单
  deleteOrder() async {
    int res = await DatabaseHelper.delete(
        'Order_table', 'order_id = ?', [orderData["order_id"]]);
    if (res != 0) {
      Get.back();
    }
  }

  /// 修改订单状态
  editOrder() async {
    int res = await DatabaseHelper.update('Order_table', {"status": stuateData},
        'order_id = ?', [orderData["order_id"]]);
    if (res != 0) {
      queryOrder();
    }
  }

  /// 修改订单物流
  editOrderLogisticsInfo(String txt) async {
    int res = await DatabaseHelper.update('Order_table',
        {"logistics_info": txt}, 'order_id = ?', [orderData["order_id"]]);
    debugPrint("res ---------- $res");
    if (res == 1) {
      await Future.delayed(Duration(milliseconds: 500)); // 延迟一会再查询
      queryOrder();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(Strem.orderDetails,
            style: Style.c_white_size18_bold, textAlign: TextAlign.left),
        backgroundColor: Style.c_8cd5ff, // 设置AppBar背景色
        automaticallyImplyLeading: false, // 确保不显示返回按钮
        actions: [
          OlderBtn.olderBtn(Icons.arrow_back, Strem.returnToTheListOfOrders,
              Style.c_3b82f6, Style.c_white, () {
            Get.back();
          })
        ],
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            if (widget.num == 0)
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    Strem.updateTheStatus,
                    style: Style.c_black87_size16_bold,
                  ),
                  Container(
                    decoration: BoxDecoration(
                        color: Style.c_back12,
                        borderRadius: BorderRadius.circular(5)),
                    child: PopupMenuButtonWidget.popupMenu(
                        _selectedStatus, scaleEndDetails(), (String newValue) {
                      setState(() {
                        _selectedStatus = newValue; // 更新选中的角色
                        if (_selectedStatus == Strem.pendingProcessing) {
                          stuateData = '1';
                        } else if (_selectedStatus == Strem.processing) {
                          stuateData = '2';
                        } else if (_selectedStatus == Strem.Shipped) {
                          stuateData = '3';
                        } else if (_selectedStatus == Strem.Delivered) {
                          stuateData = '4';
                        } else if (_selectedStatus == Strem.Cancelled) {
                          stuateData = '5';
                        }
                      });
                      editOrder();
                    }),
                  )
                ],
              ),
            _buildOrderHeader(),
            ScreenSize.height(20),
            _buildProductSection(),
            ScreenSize.height(20),
            _buildDeliveryInfo(),
            ScreenSize.height(20),
            _buildLogisticsInfo(),
            ScreenSize.height(20),
            _buildInfoRow(),
            ScreenSize.height(20),
            if (widget.num == 0) _buildActionButtons(context),
          ],
        ),
      ),
    );
  }

  /// 横向表格
  Widget rowWidget(String title, String con, bool isOrderCode) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 3),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            title,
            style: Style.c_black_size14,
          ),
          ScreenSize.width(15),
          Flexible(
            child: Text(
              con,
              style:
                  isOrderCode ? Style.c_3b82f6_size14 : Style.c_black87_size14,
            ),
          )
        ],
      ),
    );
  }

  /// 基本信息
  Widget _buildOrderHeader() {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(Strem.basicLnformation,
                style: const TextStyle(fontWeight: FontWeight.bold)),
            const Divider(),
            rowWidget(Strem.orderNumber, orderData['order_id'], true),
            rowWidget(Strem.creationTime, orderData['create_time'], false),
            rowWidget(Strem.state, judgementStatus(orderData['status']), false),
            rowWidget(Strem.customerCode, orderData['customer_code'], false),
          ],
        ),
      ),
    );
  }

  /// 操作按钮
  Widget operateBtn(String txt, Color color, Function fun) {
    return GestureDetector(
      onTap: () {
        fun();
      },
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 3),
        decoration:
            BoxDecoration(color: color, borderRadius: BorderRadius.circular(5)),
        child: Text(
          txt,
          style: TextStyle(color: Style.c_white),
        ),
      ),
    );
  }

  /// 产品信息
  Widget _buildProductSection() {
    return Card(
      child: Padding(
        padding: EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(Strem.productLnformation,
                style: const TextStyle(fontWeight: FontWeight.bold)),
            const Divider(),
            rowWidget(Strem.productName, orderData['product_name'], false),
            rowWidget(Strem.quantity, orderData['quantity'].toString(), false),
            // rowWidget(
            //     Strem.unitPrice, orderData['total_price'].toString(), false),
            rowWidget(Strem.price, orderData['total_price'].toString(), false),
          ],
        ),
      ),
    );
  }

  /// 配送信息
  Widget _buildDeliveryInfo() {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(Strem.shippingLnformation,
                style: const TextStyle(fontWeight: FontWeight.bold)),
            const Divider(),
            rowWidget(Strem.contact, userData['name'].toString(), false),
            rowWidget(Strem.contactNumber, userData['phone'].toString(), false),
            rowWidget(Strem.expectedDeliveryDate,
                orderData['expected_delivery_date'].toString(), false),
            rowWidget(
                Strem.deliveryAddress, orderData['address'].toString(), false),
          ],
        ),
      ),
    );
  }

  /// 物流信息
  Widget _buildLogisticsInfo() {
    return Card(
      child: Padding(
        padding: EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(Strem.logisticsInformation,
                style: const TextStyle(fontWeight: FontWeight.bold)),
            const Divider(),
            rowWidget(Strem.youAreHere, orderData['logistics_info'], false),
            if (_selectedStatus == Strem.Shipped && widget.num == 0)
              Align(
                alignment: Alignment.centerRight,
                child: operateBtn(Strem.modifyTheLogistics, Style.c_22c55e, () {
                  showInputDialog(context);
                }),
              )
          ],
        ),
      ),
    );
  }

  /// 备注
  Widget _buildInfoRow() {
    return Card(
      child: Padding(
        padding: EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(Strem.remarksInformation,
                style: const TextStyle(fontWeight: FontWeight.bold)),
            const Divider(),
            rowWidget(
                Strem.youAreHere, orderData['remarksInformation'] ?? "", false),
          ],
        ),
      ),
    );
  }

  // 弹出输入框的函数
  showInputDialog(BuildContext context) {
    final TextEditingController _controller = TextEditingController();
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text(Strem.modifyTheLogistics),
          content: TextField(
            controller: _controller,
          ),
          actions: <Widget>[
            TextButton(
              onPressed: () {
                _controller.text = "";
                Get.back();
              },
              child: Text(
                Strem.cancel,
                style: Style.c_black87_size14,
              ),
            ),
            TextButton(
              onPressed: () {
                setState(() {
                  content = _controller.text;
                });
                editOrderLogisticsInfo(content);
                // 获取输入的内容
                Get.back();
              },
              child: Text(
                Strem.modifyTheLogistics,
                style: Style.c_3b82f6_size14,
              ),
            ),
          ],
        );
      },
    );
  }

  /// 删除订单
  Widget _buildActionButtons(BuildContext context) {
    return GestureDetector(
      onTap: () {
        deleteOrder();
      },
      child: Container(
        margin: const EdgeInsets.only(bottom: 20),
        width: MediaQuery.of(context).size.width - 32,
        padding: const EdgeInsets.symmetric(vertical: 10),
        alignment: Alignment.center,
        decoration: BoxDecoration(
            color: Style.c_8cd5ff, borderRadius: BorderRadius.circular(5)),
        child: Text(
          Strem.deleteTheOrder,
          style: TextStyle(color: Colors.white, fontSize: 18),
        ),
      ),
    );
  }
}
